import requests
from datetime import datetime
import math
import pandas as pd
import matplotlib.pyplot as plt

listJZ = []
list_time = []
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置中文字体为黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题


# 创建图片保存目录

def go_s(data, x_labels, name):
    plt.figure(figsize=(6, 4))
    plt.plot(data, marker='o', linestyle='-', linewidth=2, markersize=2,
             color='blue',  # 线条颜色
             markerfacecolor='red',  # 标记填充颜色
             markeredgecolor='black',  # 标记边缘颜色
             markeredgewidth=1)  # 标记边缘宽度
    plt.xticks([0, len(data) - 1],
               [x_labels[0], x_labels[-1]],
               rotation=45)
    plt.title(name, fontsize=12)
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.show()


def get_gz_history(fund_code):
    for i in range(0, 6):  # 爬取12个月的历史净值
        url = f"http://api.fund.eastmoney.com/f10/lsjz?fundCode={fund_code}&pageIndex={i + 1}&pageSize=20"
        headers = {
            'Referer': 'http://fundf10.eastmoney.com',
            'User-Agent': 'Mozilla/5.0'
        }
        r = requests.get(url, headers=headers, timeout=20)
        data = r.json()['Data']['LSJZList']
        for get_ls_num in range(len(data)):
            listJZ.append(float(data[get_ls_num]['DWJZ']))  # 保存所有历史净值
            list_time.append(data[get_ls_num]['FSRQ'])  # 保存最近更新的历史净值的时间


if __name__ == '__main__':
    jj_rc = pd.read_excel(r'../Fund_form_files/JJ_模拟.xlsx', dtype={'基金代码': str, '基金名称': str, '板块': str})
    jj_code = jj_rc['基金代码'].values
    jj_name = jj_rc['基金名称'].values
    jj_type = jj_rc['板块'].values
    qu = input('基金代码(Enter一直看)：')
    if qu == '':
        for i in range(len(jj_code)):
            get_gz_history(jj_code[i])
            go_s(listJZ[::-1], list_time[::-1], f'{jj_name[i]}({jj_code[i]})')
            listJZ.clear()
    else:
        get_gz_history(qu)
        go_s(listJZ[::-1], list_time[::-1], f'{qu}')
